package cn.enjoy.tool.juc;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池关闭
 *
 * @author K
 * @date 2021-07-26 21:15
 */
public class ThreadPoolShutdown {

    public static AtomicInteger atomicInteger = new AtomicInteger(0);


    public static void main(String[] args) throws InterruptedException {
        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(4);
//        ExecutorService executorService = Executors.newCachedThreadPool();
//        ThreadPoolTaskExecutor executorService = initThreadPool(0);
        Future<?> future = null;

        CountDownLatch countDownLatch = new CountDownLatch(50000);
        for (int i = 0; i < 50000; i++) {
            // 执行多线程任务
            // start方式一 execute
            executorService.execute(() -> {
                atomicInteger.getAndIncrement();
                countDownLatch.countDown();
            });

            // start方式二 submit
//            future = executorService.submit(() -> {
//                atomicInteger.getAndIncrement();
//                countDownLatch.countDown();
//            });

            // start方式三 继承Thread或者实现Runnable，调用run
//            future = executorService.submit(() -> {
//                IncrementTask incrementTask = new IncrementTask();
//                incrementTask.run();
//            });
        }

        // 关闭线程池
        // shutdown方式一 主线程等所有子线程都执行完了，再执行后面的代码（缺点：销毁所有线程，后续再有请求进来就没有线程处理，会被拒绝掉并抛错误）
        executorService.shutdown();
        while (true) {
            if (executorService.isTerminated()) {
                break;
            } else {
                Thread.sleep(1000);
            }
        }

        // shutdown方式二 等待future任务执行完
//        while (true) {
//            if (future.isDone()) {
//                executorService.shutdown();
//                System.out.println(atomicInteger.get());
//                break;
//            } else {
//                Thread.sleep(2000);
//            }
//        }

        // shutdown方式三（有问题，关闭不了） 根据线程活跃数判断是否执行完
//        executorService.shutdown();
//        while (Thread.activeCount() > 1) {
//            Thread.yield();
//        }

        try {
            // shutdown方式零 线程计数器
            countDownLatch.await();
            System.out.println("over");
            System.out.println(atomicInteger.get());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化线程池
     *
     * @return
     */
    private static ThreadPoolTaskExecutor initThreadPool(int queueCapacity) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        // 设置最大线程数
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2);
        // 设置队列容量
        executor.setQueueCapacity(queueCapacity == 0 ? Runtime.getRuntime().availableProcessors() * 1024 : queueCapacity);

        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(10);
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        return executor;
    }

}

class IncrementTask implements Runnable {

    @Override
    public void run() {
        ThreadPoolShutdown.atomicInteger.incrementAndGet();
    }

}
